const app = getApp()
const { request } = require('../../utils/request.js');
const api = require('../../utils/api.js');
Page({
  data: {
    showCamera: false,
    cameraPosition: 'back', // 后置摄像头
    flashMode: 'off',
    isProcessing: false,
    searchValue: null,
    cameraContext: null,
    resolutionMode: 'high',
    scanFlag: false, // 高精度模式
    privacyContractName: '一拍搜题',
    showPrivacy: false,
    instructions_img: 'https://xfjf-1310081316.cos.ap-guangzhou.myqcloud.com/photo-img.png',
    privacyKey: false,
    statusBarHeight: 20, // 默认值，会在onLoad中更新
    menuButtonHeight: null,
    menuButtonTop: null,
    navBarHeight: null,
    menuPadding: null,
    showLoading: false,
    residue_count: 0,
    // 教程相关
    showTutorial: false,
    currentTutorialStep: 0,
    navPlaceholderHeight: 64,// 默认状态栏(20) + 导航栏(44)
    imageStyle: '',
    //操作演示
    videoUrl: null,
    isPlaying: false,
    hasError: false,
    errorMsg: '',
    loading: false,
    isSearch: false,
    emptyResult: '',
    resultTop: 0,
    isLetter: false,
    searchType: true,
    aiType: false,
    showModeSelector: false,
    aiAnswer: '',
    modeType: true,
    search_img: null,
  },
  closeInviteGuide(e) {
    wx.setStorageSync('hasModeGuide', true)
    this.setData({
      modeType: !wx.getStorageSync('hasModeGuide')
    })
  },
  onReady(e) {
    this.setData({
      modeType: !wx.getStorageSync('hasModeGuide'),
    })
  },
  onImageLoad(e) {
    const realWidth = e.detail.width;
    const realHeight = e.detail.height;
    const scale = 750 / realWidth;
    const displayHeight = realHeight * scale;

    this.setData({
      imageStyle: `width: 750rpx; height: ${displayHeight}rpx;`
    });
  },
  onLoad: function () {
    try {
      const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
      const systemInfo = wx.getSystemInfoSync();
      const navHeight = (systemInfo.statusBarHeight + menuButtonInfo.height)
        + ((menuButtonInfo.top - systemInfo.statusBarHeight) * 2);

      // 计算导航占位高度
      const navPlaceholderHeight = systemInfo.statusBarHeight + (systemInfo.platform === 'android' ? 48 : 44);

      this.setData({
        navBarHeight: navHeight,
        statusBarHeight: systemInfo.statusBarHeight,
        menuButtonHeight: menuButtonInfo.height,
        menuButtonTop: menuButtonInfo.top,
        menuPadding: ((menuButtonInfo.top - systemInfo.statusBarHeight)),
        navPlaceholderHeight: navPlaceholderHeight,
        videoUrl: app.globalData.operation,
      });
      app.getConfig("is_letter", res => {
        const isLetter = res.is_public && res.value
        this.setData({ isLetter })
      })
    } catch (e) {
      console.error('获取状态栏高度失败', e);
      // 设置默认值
      this.setData({
        statusBarHeight: 20,
        navBarHeight: 44,
        menuButtonHeight: 32,
        navPlaceholderHeight: 64 // 默认状态栏(20) + 导航栏(44)
      });
    }

    const _ = this
    wx.getPrivacySetting({
      success(res) {
        if (res.errMsg == "getPrivacySetting:ok") {
          _.setData({
            privacyContractName: res.privacyContractName,
            showPrivacy: res.needAuthorization
          })
        }
      }
    })
    _.setData({
      privacyKey: wx.getStorageSync('privacyKey')
    })

    // 检查是否首次进入
    this.checkFirstTimeUse();
    this.getElementHeight('#buttomTop'); // 推荐在 onReady 调用，元素已渲染
  },

  getElementHeight(selector) {
    wx.createSelectorQuery()
      .select(selector)
      .boundingClientRect(rect => {
        if (rect) {
          console.log('元素高度：', rect.top);
          this.setData({
            resultTop: rect.height + 20
          })
        } else {
          console.warn('找不到元素');
        }
      })
      .exec();
  },

  tutorialBtn() {
    this.setData({ showTutorial: true, })
  },
  addUgaat() {
    app.goPayPage()
  },
  tuPrivacy() {
    wx.navigateTo({
      url: '/pages/privacy/index',
    })
  },
  // 检查是否是首次使用
  checkFirstTimeUse: function () {
    const hasShownTutorial = wx.getStorageSync('hasShownPhotoTutorial');
    if (!hasShownTutorial) {
      this.setData({
        showTutorial: true
      });
    }
  },

  // 完成教程处理
  completeTutorial: function () {
    // 设置标记，表示已经显示过教程
    wx.setStorageSync('hasShownPhotoTutorial', true);
    this.setData({
      showTutorial: false
    });
  },
  switchChange(e) {
    this.setData({
      aiType: e.detail.value
    })
  },
  // 新增：打开模式选择弹窗
  openModeSelector() {
    this.setData({ showModeSelector: true })
  },
  // 新增：关闭模式选择弹窗
  closeModeSelector() {
    this.setData({ showModeSelector: false })
  },
  // 新增：设置模式
  setMode(e) {
    const mode = e.currentTarget.dataset.mode
    const isAi = mode === 'ai'
    this.setData({ aiType: isAi, showModeSelector: false })
    // 与原有switchChange保持一致的行为（不触发额外副作用）
  },
  onHide() {
    var that = this
    that.setData({
      showLoading: false
    })

    this.hideGlobalLoading()
  },
  onShow: function () {
    // 设置tabbar选中状态
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1 // 拍照对应索引1
      });
    }
    var that = this
    that.setData({
      showLoading: false,
    })
    this.hideGlobalLoading()
    this.fetchUnreadCount()
    this.checkFirstTimeUse();
  },
  // 获取未读消息数量
  fetchUnreadCount: function () {
    request(api.userUsageCount + '?user_id=' + wx.getStorageSync('userId'), 'GET')
      .then(res => {
        this.setData({
          residue_count: res.data.usage_count
        });
      })
      .catch(err => {
        console.error('获取usage_count失败', err);
      });

  },
  exitMiniProgram() {
    // 显示确认提示，提升用户体验
    wx.showModal({
      title: '确认退出',
      content: '如不同意隐私政策，将无法使用小程序服务',
      confirmText: '仍要退出',
      cancelText: '重新考虑',
      confirmColor: '#ff4d4f',
      success: (res) => {
        if (res.confirm) {
          wx.exitMiniProgram({
            success: (res) => {
              console.log('小程序已退出', res);
            },
            fail: (err) => {
              console.error('退出小程序失败', err);
              // 退出失败时的备用方案
              wx.showToast({
                title: '退出失败，请手动关闭',
                icon: 'none',
                duration: 2000
              });
            }
          });
        }
      }
    });
  },
  // 隐私协议同意的回调函数
  handleAgreePrivacyAuthorization: function (e) {
    console.log('用户同意隐私授权', e);
    const _ = this
    // 添加loading状态提升用户体验
    wx.showLoading({
      title: '处理中...',
      mask: true
    });

    // 稍微延迟，让用户看到反馈
    setTimeout(() => {
      wx.setStorageSync('privacyKey', true)
      _.setData({
        privacyKey: wx.getStorageSync('privacyKey'),
        showPrivacy: false  // 明确关闭弹窗
      })
      wx.hideLoading();

      // 显示成功提示
      wx.showToast({
        title: '授权成功',
        icon: 'success',
        duration: 1500
      });
    }, 300);
  },

  // 防止弹窗背景滚动
  preventTouchMove: function (e) {
    // 阻止触摸事件穿透
    return false;
  },

  // 防止点击弹窗内容区域关闭弹窗
  preventClose: function (e) {
    // 阻止事件冒泡
    e.stopPropagation();
  },
  openPrivacyContract() {
    wx.navigateTo({
      url: '/pages/privacy/index',
    })
  },
  //用户拒绝授权处理方法：
  showModal() {
    let that = this
    //弹出弹窗让用户点击"点击跳转"按钮到设置页面
    wx.showModal({
      content: "当前页面功能需打开相机权限，请点击跳转设置",
      showCancel: true,
      confirmText: "点击跳转",
      success: (res => {
        if (res.confirm) {
          //用户点击"点击跳转"调用goAuth函数
          that.goAuth()
        }
      }),
    })
  },
  goAuth() {
    let that = this
    wx.openSetting({
      success: (res => {
        if (!res.authSetting["scope.camera"]) {
          that.showModal()
        } else {
        }
      })
    })
  },
  // 打开自定义相机界面
  goToCustomCamera: function () {
    // 检查是否完成了教程
    // const hasShownTutorial = wx.getStorageSync('hasShownPhotoTutorial');
    // if (!hasShownTutorial) {
    //   this.setData({
    //     showTutorial: true
    //   });
    //   return;
    // }
    const that = this;
    wx.authorize({
      scope: 'scope.camera',
      success: (res => {
        this.setData({
          showCamera: true
        });
      }),
      fail: (res => {
        that.showModal()
      }),
    })
  },
  goAuth() {
    wx.authorize({
      scope: 'scope.camera',
      success: () => {
        console.log('已授权摄像头')
      },
      fail: () => {
        wx.showModal({
          title: '摄像头权限未开启',
          content: '请在设置中打开摄像头权限，否则无法使用相关功能',
          success: (res) => {
            if (res.confirm) {
              wx.openSetting()
            }
          }
        })
      }
    })
  },
  onPhotoTaken(e) {
    this.closeCamera()
    let imagePath = e.detail
    const isAi = this.data.aiType
    if (isAi) {
      this.aiRequest(imagePath)
      return
    }
    this.uploadImage(imagePath)
  },
  closeCamera(e) {
    this.setData({
      showCamera: false,
      searchType: false
    });
  },
  errorCamera(e) {
    this.setData({
      showCamera: false,
      searchType: false
    });
  },

  uploadImage: function (filePath) {
    var that = this
    that.setData({
      showLoading: true,
      search_img: filePath
    })
    try {

      app.uploadFile(filePath, {
        // 可以在这里添加额外的表单数据
      }, function (data) {
        // 无论成功失败，都结束loading
        if (data) {
          try {
            that.processResults(data);
          } catch (error) {
            console.error('解析响应失败:', error);
            that.processResults(null);
            wx.showToast({
              title: '识别失败',
              icon: 'none'
            });
          }
        } else {
          that.processResults(null);
          // 上传失败
          console.log('上传失败');
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          });
        }
      }, function () {
        // 添加取消上传的回调
        console.log('上传已取消');
        that.setData({
          showLoading: false
        })
      });
    } catch (error) {
      that.processResults(null);
      console.error('上传过程发生错误:', error);
      wx.showToast({
        title: '上传发生错误',
        icon: 'none'
      });
    }
  },
  chuckResidueCount() {
    return this.data.residue_count && this.data.residue_count > 1
  },
  // 跳转到相册选择
  goToAlbum: function () {
    // 检查是否完成了教程
    // const hasShownTutorial = wx.getStorageSync('hasShownPhotoTutorial');
    // if (!hasShownTutorial) {
    //   this.setData({
    //     showTutorial: true
    //   });
    //   return;
    // }

    if (!this.chuckResidueCount()) {
      wx.showToast({
        title: '您的次数已经用完啦',
        icon: 'error'
      })
      return;
    }

    const isAi = this.data.aiType

    // 已完成教程，正常打开相册
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album'],
      success: (res) => {
        const tempImagePath = res.tempFiles[0].tempFilePath;
        if (isAi) {
          this.aiRequest(tempImagePath)
          return
        }
        this.uploadImage(tempImagePath)
      }
    });
  },

  aiRequest: function (filePath) {
    var that = this;
    that.setData({
      showLoading: true,
      search_img: filePath
    });

    try {
      app.uploadFileAi(filePath, {
        // 可传额外表单参数
      }, function (data) {
        const newData = {
          showLoading: false,
          loading: false,
          isSearch: true,
          errorMsg: ''
        };
        if (data) {
          try {
            if (data.code !== 1) {
              newData.errorMsg = '识别失败';
              wx.showToast({
                title: '识别失败',
                icon: 'none'
              });
            } else {
              newData.aiAnswer = data.ai_result;
            }
          } catch (error) {
            console.error('解析响应失败:', error);
            newData.errorMsg = '解析失败';
            wx.showToast({
              title: '解析失败',
              icon: 'none'
            });
          }
        } else {
          console.log('上传失败');
          newData.errorMsg = '上传失败';
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          });
        }

        that.setData(newData);
      }, function () {
        // 取消上传
        that.setData({
          showLoading: false
        });
      });
    } catch (error) {
      console.error('上传过程发生错误:', error);
      that.setData({
        showLoading: false,
        loading: false,
        isSearch: true,
        errorMsg: '上传过程发生错误'
      });
      wx.showToast({
        title: '上传发生错误',
        icon: 'none'
      });
    }
  },

  /**
   * 处理公告点击事件
   */
  handleAnnouncementTap() {
    wx.showModal({
      title: '使用须知',
      content: '请仔细阅读使用说明，确保符合要求。拍摄或选择照片时，确保题目文字清晰可见。',
      showCancel: false,
      confirmText: '我知道了'
    });
  },
  onPlayVideo() {
    this.setData({
      isPlaying: true
    });
  },
  onCloseVideo() {
    this.setData({
      isPlaying: false,
    });
  },
  onPreventClose(e) {
    e.stopPropagation();
  },
  hideGlobalLoading() {
    const loadingComponent = this.selectComponent('#globalLoading');
    if (loadingComponent) {
      loadingComponent.hide(); // 调用子组件的 show() 方法
    }
  },
  onUnload() {
    this.hideGlobalLoading()
  },
  // 处理解析结果数据的方法，封装你原来的逻辑
  processResults(parsedData) {
    const that = this;
    const newData = { showLoading: false };

    if (parsedData && parsedData.error) {
      Object.assign(newData, {
        hasError: true,
        errorMsg: parsedData.error,
        loading: false,
        isSearch: true,
      });
      that.setData(newData);
      return;
    }

    if (parsedData && parsedData.keyword) {
      newData.keyword = parsedData.keyword;

      if (parsedData.results && parsedData.results.length > 0) {
        const processedResults = parsedData.results.map(item => {
          const answerList = that.formatAnswerToArray(item.answer || '');
          const correctOptionsText = [];

          if (answerList.includes('1') && item.optionA) correctOptionsText.push(item.optionA);
          if (answerList.includes('2') && item.optionB) correctOptionsText.push(item.optionB);
          if (answerList.includes('3') && item.optionC) correctOptionsText.push(item.optionC);
          if (answerList.includes('4') && item.optionD) correctOptionsText.push(item.optionD);


          console.log(correctOptionsText);
          return {
            ...item,
            answerList,
            correctOptionsText,
            showSolve: false,
          };
        });


        Object.assign(newData, {
          results: processedResults,
          emptyResult: false,
          loading: false,
          isSearch: true,
          hasError: false,
        });
      } else {
        Object.assign(newData, {
          emptyResult: true,
          loading: false,
          isSearch: true,
        });
      }
    } else {
      Object.assign(newData, {
        hasError: true,
        errorMsg: '未查询到',
        loading: false,
        isSearch: true,
      });
    }
    // ✅ 只调用一次 setData，提高性能
    that.setData(newData);
  },
  // 将答案格式化为数组
  formatAnswerToArray: function (answer) {
    if (!answer) return [];

    // 处理答案中可能有的空格和中文逗号
    answer = String(answer).replace(/，/g, ',').replace(/\s+/g, '');

    // 将答案分割成数组
    return answer.split(',');
  },

  // 格式化答案，将数字转换为字母
  formatAnswer: function (answer) {
    if (!answer) return '';

    // 处理答案中可能有的空格和中文逗号
    answer = String(answer).replace(/，/g, ',').replace(/\s+/g, '');

    // 将答案分割成数组
    const parts = answer.split(',');

    // 转换每个数字为对应字母
    const letters = parts.map(num => {
      switch (num) {
        case '1': return 'A';
        case '2': return 'B';
        case '3': return 'C';
        case '4': return 'D';
        default: return num; // 保留不是1-4的原始值
      }
    });
    // 返回转换后的字母，用逗号和空格连接
    return letters.join(', ');
  },
  /**
 * 图片预览
 */
  previewImage(e) {
    const url = e.currentTarget.dataset.url;
    wx.previewImage({
      urls: [url],
      current: url
    });
  },
  /**
 * 反馈错题
 */
  feedback() {
    wx.showModal({
      title: '反馈错题',
      content: '确认要反馈此题目有误吗？',
      success: (res) => {
        if (res.confirm) {
          const { keyword, user_id } = this.data
          request(api.feedback, 'post', {
            'content': keyword,
            'user_id': user_id
          })
          wx.showToast({
            title: '反馈成功，谢谢！',
            icon: 'success'
          });
        }
      }
    });
  },

  onQuestion() {
    const searchType = this.data.searchType
    if (searchType) {
      this.goToAlbum()
    } else {
      this.goToCustomCamera()
    }
  }

}); 